/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-12-21     Yanzr       the first version
 */
#include "key_app.h"

#define KEY_PIN1 GET_PIN(B,0)
#define KEY_PIN2 GET_PIN(B,1)
#define KEY_PIN3 GET_PIN(B,2)
#define KEY_PIN4 GET_PIN(A,0)

uint8_t key_val;
uint8_t key_old;
uint8_t key_down;
uint8_t key_up;

uint8_t key_read(void)
{
    uint8_t temp=0;
    if(rt_pin_read(KEY_PIN1)==PIN_LOW)
        temp=1;
    if(rt_pin_read(KEY_PIN2)==PIN_LOW)
        temp=2;
    if(rt_pin_read(KEY_PIN3)==PIN_LOW)
        temp=3;
    if(rt_pin_read(KEY_PIN4)==PIN_LOW)
        temp=4;
    return temp;
}

void key_proc(void *parameter)
{
    while(1)
    {
       key_val=key_read();
       key_up=key_val&(key_val^key_old);
       key_down=~key_val&(key_val^key_old);
       key_old=key_val;
       if(key_down!=0)
       {
           rt_mutex_take(ucled_mutex, RT_WAITING_FOREVER);
           ucled[0]^=1;
           rt_mutex_release(ucled_mutex);
       }

       rt_thread_mdelay(10);

    }

}

void key_init(void)
{
    rt_pin_mode(KEY_PIN1, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_PIN2, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_PIN3, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_PIN4, PIN_MODE_INPUT_PULLUP);

    rt_thread_t key_thread = rt_thread_create("key_proc",key_proc,RT_NULL,1024,20,10);
    if(key_thread!=RT_NULL)
       rt_thread_startup(key_thread);

}
